package com.lineng.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lineng.service.LoginService;
import com.lineng.util.SessionListener;
import com.lineng.util.VerificationUtil;

@Controller
public class LoginController {
	@Autowired
	LoginService loginService;

	/**
	 * 登录
	 * 
	 * @param username
	 * @param password
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> loginUser(String username, String password, HttpServletResponse response,
			HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		if (loginService.loginUser(username, password) != null) {
			// 创建session并把用户的信息保存到session
			request.getSession().setAttribute("permission", loginService.loginUser(username, password).getPermission());
			request.getSession().setAttribute("username", username);
			map.put("status", "1");
			map.put("permission", loginService.loginUser(username, password).getPermission());
			// 登录验证，防止用户重复登录
			SessionListener.checkUser(username, request);
		} else {
			map.put("status", "0");
		}
		return map;
	}

	/**
	 * 刷新验证
	 * 
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/verification", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> verification(HttpServletResponse response, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (VerificationUtil.verification(request) == 1) {
			map.put("username", request.getSession().getAttribute("username"));
			map.put("permission", request.getSession().getAttribute("permission"));
			map.put("status", "1");
			return map;
		}
		map.put("status", "0");
		return map;
	}

	/**
	 * 退出登录
	 * 
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "/loginOut", method = RequestMethod.GET)
	@ResponseBody
	public void LoginOut(HttpServletResponse response, HttpServletRequest request) {
		if (request.getSession(false) != null && request.getSession().getAttribute("username") != null) {
			request.getSession().removeAttribute("permission");
			request.getSession().removeAttribute("username");
			request.getSession().invalidate();
		}
	}
}
